package com.tfswx.jcyw.dmzc.window;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.intellij.icons.AllIcons.Actions;
import com.intellij.icons.AllIcons.General;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.actionSystem.ex.CheckboxAction;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import com.intellij.util.xml.ui.DomColumnInfo;
import com.tfswx.jcyw.dmzc.api.ApiUtil;
import com.tfswx.jcyw.dmzc.api.dto.*;
import com.tfswx.jcyw.dmzc.bean.Gbc;
import com.tfswx.jcyw.dmzc.component.AbstractFilterPopup;
import com.tfswx.jcyw.dmzc.exception.NotLoginException;
import com.tfswx.jcyw.dmzc.service.DlxxService;
import com.tfswx.jcyw.dmzc.service.XmxxService;
import com.tfswx.jcyw.dmzc.util.NotificationUtil;
import com.tfswx.jcyw.dmzc.util.ProjectUtil;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.ChangeListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

@Service
public final class DmpsjlQueryWindow extends SimpleToolWindowPanel {
//    private final Map<String, AbstractFilterPopup.SelectAble> dmzcFilterItems;

    //    private boolean zjkf = false;
//    private boolean zjzc = false;
//    private String sfxg = null;
    private final DlxxService dlxx = DlxxService.getInstance();
    private final XmxxService XMXX;
    private final Project project;
    @Nullable
    private JTable zcjlTable;
    @Nullable
    private JPanel windowPanel;
    @Nullable
    private JScrollPane mainScrollPane;

    public DmpsjlQueryWindow(@NotNull Project project) {
        super(true, false);
        this.project = project;
//        this.dmzcFilterItems = new ConcurrentHashMap<>();
        this.XMXX = XmxxService.getInstance(this.project).getState();
        mainScrollPane.setBorder(BorderFactory.createEmptyBorder());
        DefaultTableCellRenderer centerTableCellRenderer = new DefaultTableCellRenderer();
        centerTableCellRenderer.setHorizontalAlignment(0);
        zcjlTable.setDefaultRenderer(Object.class, centerTableCellRenderer);
        final ListTableModel<DmpslbQueryResult> jTableModel = new ListTableModel<>(
                new DomColumnInfo<DmpslbQueryResult, String>("序号") {
                    @Nullable
                    @Override
                    public String valueOf(@NotNull DmpslbQueryResult zcjllbDTO) {
                        return zcjllbDTO.getXh();
                    }

                    @Override
                    public int getWidth(JTable table) {
                        return 40;
                    }
                },
                new DomColumnInfo<DmpslbQueryResult, String>("评审文件") {
                    @Nullable
                    @Override
                    public String valueOf(@NotNull DmpslbQueryResult item) {
                        return item.getZcywjbh();
                    }

                },
                new DomColumnInfo<DmpslbQueryResult, String>("选区范围") {
                    @Nullable
                    @Override
                    public String valueOf(@NotNull DmpslbQueryResult item) {
                        String zcywjbh = item.getZcywjbh();
                        if (zcywjbh == null) {
                            return null;
                        }
                        if (zcywjbh.contains(":")) {
                            return zcywjbh.split(":")[1];
                        }
                        return null;
                    }

                    @Override
                    public int getWidth(JTable table) {
                        return 60;
                    }
                },
                new DomColumnInfo<DmpslbQueryResult, String>("评审人员") {
                    @Nullable
                    @Override
                    public String valueOf(@NotNull DmpslbQueryResult item) {
                        return item.getZcrymc();
                    }

                    @Override
                    public int getWidth(JTable table) {
                        return 60;
                    }

                },
                new DomColumnInfo<DmpslbQueryResult, String>("开发人员") {
                    @Nullable
                    @Override
                    public String valueOf(@NotNull DmpslbQueryResult item) {
                        return item.getKfrymc();
                    }

                    @Override
                    public int getWidth(JTable table) {
                        return 60;
                    }

                },
                new DomColumnInfo<DmpslbQueryResult, String>("评审意见") {
                    @Nullable
                    @Override
                    public String valueOf(@NotNull DmpslbQueryResult item) {
                        return item.getZcyj();
                    }

                },
                new DomColumnInfo<DmpslbQueryResult, String>("意见等级") {
                    @Nullable
                    @Override
                    public String valueOf(@NotNull DmpslbQueryResult item) {
                        return item.getYjdj();
                    }

                    @Override
                    public int getWidth(JTable table) {
                        return 60;
                    }

                },
                new DomColumnInfo<DmpslbQueryResult, String>("评审时间") {
                    @Nullable
                    @Override
                    public String valueOf(@NotNull DmpslbQueryResult item) {
                        return DateUtil.format(item.getCjsj(), DatePattern.NORM_DATETIME_FORMAT);
                    }

                    @Override
                    public int getWidth(JTable table) {
                        return 130;
                    }

                },
                new DomColumnInfo<DmpslbQueryResult, String>("是否修改") {
                    @Nullable
                    @Override
                    public String valueOf(@NotNull DmpslbQueryResult item) {
                        String sfxg = item.getSfxg();
                        if (StringUtils.isBlank(sfxg)) {
                            return null;
                        }
                        return "Y".equals(sfxg) ? "是" : "否";
                    }

                    @Override
                    public int getWidth(JTable table) {
                        return 60;
                    }

                });
        zcjlTable.setModel(jTableModel);
        JTableHeader tableHeader = zcjlTable.getTableHeader();
        tableHeader.setReorderingAllowed(false);
        zcjlTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);

        TableColumnModel columnModel = zcjlTable.getColumnModel();
        ColumnInfo<DmpslbQueryResult, String>[] columnInfos = jTableModel.getColumnInfos();
        int columnCount = columnModel.getColumnCount();
        for (int i = 0; i < columnCount; i++) {
            TableColumn column = columnModel.getColumn(i);
            column.setResizable(false);
            int width = columnInfos[i].getWidth(zcjlTable);
            System.out.println(i + "----->" + width);
            if (width > 0) {
                column.setMaxWidth(width);
                column.setPreferredWidth(width);
            }
        }

        zcjlTable.setRowHeight(25);
        zcjlTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(@NotNull MouseEvent e) {
                int selectedRow = zcjlTable.rowAtPoint(e.getPoint());
                if (selectedRow != -1) {
                    int selRow = zcjlTable.getSelectedRow();
                    if (selRow != selectedRow) {
                        zcjlTable.setRowSelectionInterval(selectedRow, selectedRow);
                    }

                    final DmpslbQueryResult item = jTableModel.getItem(selectedRow);
                    DmzcGetOutputDTO zcjl = getZcjl(item.getZcbh());
                    if (zcjl == null) {
                        return;
                    }
                    if (e.getButton() == 1 && e.getClickCount() == 2) {
                        ProjectUtil.openFileInEditor(project, zcjl.getZcywjbh());
                    } else if (e.getButton() == 3) {
                        JPopupMenu popupMenu = new JPopupMenu();
                        JMenuItem ckxqMenuItem = new JMenuItem();
                        ckxqMenuItem.setIcon(General.InspectionsEye);
                        ckxqMenuItem.setText("查看详情");
                        ckxqMenuItem.addActionListener(actionEvent -> (new DmzcjlViewWindow(zcjl)).show());
                        popupMenu.add(ckxqMenuItem);
                        JMenuItem bjwjMenuItem = new JMenuItem();
                        bjwjMenuItem.setIcon(Actions.EditSource);
                        bjwjMenuItem.setText("编辑文件");
                        bjwjMenuItem.addActionListener(actionEvent -> ProjectUtil.openFileInEditor(project, zcjl.getZcywjbh()));
                        popupMenu.add(bjwjMenuItem);
                        JMenuItem deleteMenuItem = new JMenuItem();
                        deleteMenuItem.setIcon(Actions.GC);
                        deleteMenuItem.setText("删除");
                        deleteMenuItem.addActionListener(actionEvent -> {
                            if (!dlxx.getRybm().equals(item.getZcrybm())) {
                                Messages.showWarningDialog("无法删除别人的评审记录", "警告");
                            }

                            boolean b = (new ConfirmDialog("警告", "是否删除？")).showAndGet();
                            if (b) {
                                deleteDmzc(item.getZcbh());
                            }

                        });
                        if (dlxx.getRybm().equals(item.getZcrybm())) {
                            popupMenu.add(deleteMenuItem);
                        }

                        popupMenu.show(e.getComponent(), e.getX(), e.getY());
                    }
                }
            }
        });
        ActionToolbar toolbar = this.initToolbar();
        this.setToolbar(toolbar.getComponent());
        String fwdz = ApiUtil.base;
        if (StringUtils.isNotBlank(fwdz)) {
            this.queryPsjl();
        }

        this.setContent(windowPanel);
    }

    private ActionToolbar initToolbar() {
        DefaultActionGroup group = new DefaultActionGroup();
        group.add(new CheckboxAction("我开发的") {

            @Override
            public boolean isSelected(@NotNull AnActionEvent e) {
                return XMXX.isPsZjkf();
            }

            @Override
            public void setSelected(@NotNull AnActionEvent e, boolean state) {
                XMXX.setPsZjkf(state);
                queryPsjl();
            }
        });
        group.add(new CheckboxAction("我评审的") {

            @Override
            public boolean isSelected(@NotNull AnActionEvent e) {
                return XMXX.isPsZjzc();
            }

            @Override
            public void setSelected(@NotNull AnActionEvent e, boolean state) {
                XMXX.setPsZjzc(state);
                queryPsjl();
            }
        });
//        group.add(new CheckboxAction("当前文件") {
//
//            @Override
//            public boolean isSelected(@NotNull AnActionEvent e) {
//                return xmxx.isDqwj();
//            }
//
//            @Override
//            public void setSelected(@NotNull AnActionEvent e, boolean state) {
//                xmxx.setDqwj(state);
//                queryZcjl();
//            }
//        });
//        group.add(new ComboBoxAction() {
//            {
//                getTemplatePresentation().setText("修改状态-全部");
//                if ("Y".equals(xmxx.getSfxg())) {
//                    getTemplatePresentation().setText("修改状态-已修改");
//                } else if ("N".equals(xmxx.getSfxg())) {
//                    getTemplatePresentation().setText("修改状态-未修改");
//                }
//                setToolTipText("是否修改");
//            }
//
//            private ComboBoxButton comboBoxButton;
//
//            @Override
//            protected ComboBoxButton createComboBoxButton(Presentation presentation) {
//                comboBoxButton = super.createComboBoxButton(presentation);
//                return comboBoxButton;
//            }
//
//            @Override
//            protected @NotNull DefaultActionGroup createPopupActionGroup(JComponent button) {
//                DefaultActionGroup defaultActionGroup = new DefaultActionGroup();
//                defaultActionGroup.add(new AnAction("修改状态-全部") {
//                    @Override
//                    public void actionPerformed(@NotNull AnActionEvent e) {
//                        comboBoxButton.setText("修改状态-全部");
//                        xmxx.setSfxg(null);
//                        queryZcjl();
//                    }
//                });
//                defaultActionGroup.add(new AnAction("修改状态-已修改") {
//                    @Override
//                    public void actionPerformed(@NotNull AnActionEvent e) {
//                        comboBoxButton.setText("修改状态-已修改");
//                        xmxx.setSfxg("Y");
//                        queryZcjl();
//                    }
//                });
//                defaultActionGroup.add(new AnAction("修改状态-未修改") {
//                    @Override
//                    public void actionPerformed(@NotNull AnActionEvent e) {
//                        comboBoxButton.setText("修改状态-未修改");
//                        xmxx.setSfxg("N");
//                        queryZcjl();
//                    }
//                });
//                return defaultActionGroup;
//            }
//        });
        group.add(new DumbAwareAction(() -> "更多筛选项", General.Filter) {
            @NotNull
            private final AbstractFilterPopup popup = new AbstractFilterPopup() {
                private JTextField psjhbhTextField = new JTextField();

                @Override
                public void onClose() {
                    String text = psjhbhTextField.getText();
                    XMXX.setPsjhbh(text);
                    queryPsjl();
                }

                @Override
                public Component initCenterComponent() {
                    JPanel jPanel = new JPanel(new GridBagLayout());
                    psjhbhTextField.setText(XMXX.getPsjhbh());
                    // 第一行
                    jPanel.add(new JLabel("评审计划编号"), new Gbc(1, 1));
                    jPanel.add(psjhbhTextField, new Gbc(2, 1, 3, 1));

                    // 第二行
                    jPanel.add(new JLabel("修改状态"), new Gbc(1, 2));
                    JRadioButton qb = new JRadioButton("全部");
                    JRadioButton yxg = new JRadioButton("已修改");
                    JRadioButton wxg = new JRadioButton("未修改");
                    ButtonGroup bg = new ButtonGroup();
                    bg.add(qb);
                    bg.add(yxg);
                    bg.add(wxg);
                    if ("Y".equals(XMXX.getPsSfxg())) {
                        bg.setSelected(yxg.getModel(), true);
                    } else if ("N".equals(XMXX.getPsSfxg())) {
                        bg.setSelected(wxg.getModel(), true);
                    } else {
                        bg.setSelected(qb.getModel(), true);
                    }
                    ChangeListener listener = e -> {
                        JRadioButton source = (JRadioButton) e.getSource();
                        if (!source.isSelected()) {
                            return;
                        }
                        if (source == wxg) {
                            XMXX.setPsSfxg("N");
                        } else if (source == yxg) {
                            XMXX.setPsSfxg("Y");
                        } else {
                            XMXX.setPsSfxg(null);
                        }
                    };
                    qb.addChangeListener(listener);
                    wxg.addChangeListener(listener);
                    yxg.addChangeListener(listener);
                    jPanel.add(qb, new Gbc(2, 2));
                    jPanel.add(yxg, new Gbc(3, 2));
                    jPanel.add(wxg, new Gbc(4, 2));

                    // 第三行
                    jPanel.add(new JLabel("当前文件"), new Gbc(1, 3));
                    JCheckBox checkbox = new JCheckBox();
                    checkbox.setSelected(XMXX.isPsDqwj());
                    jPanel.add(checkbox, new Gbc(2, 3));

                    setLayout(new BorderLayout());
                    removeAll();
                    return jPanel;
                }
            };

            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
                MouseEvent inputEvent = (MouseEvent) e.getInputEvent();
                Component component = inputEvent.getComponent();
                popup.show(component, 0, component.getHeight());
            }
        });


        group.add(new DumbAwareAction() {
            {
                this.getTemplatePresentation().setText("查询");
                this.getTemplatePresentation().setIcon(Actions.Search);
            }

            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
                queryPsjl();
            }
        });
        group.addSeparator();
        group.add(new DumbAwareAction() {
            {
                this.getTemplatePresentation().setText("打开设置");
                this.getTemplatePresentation().setIcon(General.Settings);
            }

            @Override
            public void actionPerformed(@NotNull AnActionEvent e) {
                DmzcSettingWindow.openSetting(project);
            }
        });
        ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("toolbar", group, true);
        toolbar.setTargetComponent(this);
        return toolbar;
    }

    private DmzcGetOutputDTO getZcjl(String zcbh) {
        DmzcGetInputDTO dmzcGetInputDTO = new DmzcGetInputDTO();
        dmzcGetInputDTO.setZcbh(zcbh);
        return ApiUtil.fwdApi.getDmzc(dmzcGetInputDTO);
    }

    private void deleteDmzc(String zcbh) {
        DmzcDeleteInputDTO dmzcDeleteInputDTO = new DmzcDeleteInputDTO();
        dmzcDeleteInputDTO.setZcbh(zcbh);
        ApiUtil.fwdApi.deleteDmzc(dmzcDeleteInputDTO);
        Notification notification = NotificationUtil.create("评审记录删除成功！", "代码评审", NotificationType.INFORMATION);
        notification.notify(this.project);
        this.queryPsjl();
    }

    public void queryPsjl() {
        DmpslbQueryParam queryParam = new DmpslbQueryParam();
        queryParam.setGcmc(project.getName());
        queryParam.setXmlx(this.XMXX.getXmlx());
        if (XMXX.isPsZjkf()) {
            queryParam.setKfrybm(this.dlxx.getRybm());
        }

        if (XMXX.isPsZjzc()) {
            queryParam.setZcrybm(this.dlxx.getRybm());
        }

        queryParam.setPsjhbh(XMXX.getPsjhbh());

        List<DmpslbQueryResult> queryResultArrayList = new ArrayList<>();

        try {
            if (XMXX.isPsDqwj()) {
                queryParam.setZcywjbh(ProjectUtil.getOpenFilePath(project));
            }
            queryParam.setSfxg(XMXX.getPsSfxg());

            PageParam<DmpslbQueryParam> dmzclbQueryParamPageParam = new PageParam<>();
            dmzclbQueryParamPageParam.setPageNum(1);
            dmzclbQueryParamPageParam.setPageSize(Integer.MAX_VALUE);
            dmzclbQueryParamPageParam.setFilter(queryParam);
            PageResult<DmpslbQueryResult> dmpslbQueryResultPageResult = ApiUtil.fwdApi.queryDmpslb(dmzclbQueryParamPageParam);
            queryResultArrayList = dmpslbQueryResultPageResult.getList();
        } catch (NotLoginException e) {
            NotificationUtil.showLogin(project);
        } catch (Exception e) {
            Notification notification = NotificationUtil.create("评审记录查询失败：" + e.getMessage(), "代码评审", NotificationType.ERROR);
            notification.notify(this.project);
        }

        for (int i = 0; i < queryResultArrayList.size(); i++) {
            queryResultArrayList.get(i).setXh(String.valueOf(i + 1));
        }

        ListTableModel<DmpslbQueryResult> model = (ListTableModel<DmpslbQueryResult>) zcjlTable.getModel();
        if (model == null) {
            throw new NullPointerException("没有获取到表格model");
        }
        model.setItems(queryResultArrayList);
    }
}
